package itbour.onetouchshow.activity.version1_4;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import itbour.onetouchshow.App;
import itbour.onetouchshow.AppCache;
import itbour.onetouchshow.R;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.constants.DataCreater;
import itbour.onetouchshow.singlecase.InchingDataSingleCase;
import itbour.onetouchshow.utils.GetPath;
import itbour.onetouchshow.utils.aliyun.AliRequestUtils;
import itbour.onetouchshow.utils.crop.BaseLayerView;
import itbour.onetouchshow.utils.crop.BitmapUtils;
import itbour.onetouchshow.utils.crop.EnjoyCropLayout;
import itbour.onetouchshow.utils.crop.clippath.ClipPathLayerView;
import itbour.onetouchshow.utils.crop.clippath.ClipPathRectangle;
import itbour.onetouchshow.utils.crop.mask.ColorMask;

/**
 * Created by guoh on 2018/4/9.
 * 功能描述：图片裁剪
 * 需要的参数：图片地址 裁剪框宽高
 */

public class ImageClipActivity extends MVPBaseActivity {

    public static final String FILE_PATH = "FILE_PATH";
    private static final String CLIP_WIDTH = "CLIP_WIDTH";
    private static final String CLIP_HEIGHT = "CLIP_HEIGHT";
    @BindView(R.id.crop_layout)
    EnjoyCropLayout cropLayout;
    @BindView(R.id.btn_cancel)
    Button btnCancel;
    @BindView(R.id.btn_choose)
    Button btnChoose;
    private String filePath;
    private int width;
    private int height;

    //default value
    private double imgNodeSizeMultiple = 5000000;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    dismissProgressDialog();
                    showImageTooBigDialog();
                    break;
                case 2:
                    dismissProgressDialog();
                    showImageShouldCropDialog();
                    break;
            }
        }
    };

    public static Intent getLaunchIntent(Context context, String path, int width, int height) {
        Intent intent = new Intent(context, ImageClipActivity.class);
        intent.putExtra(FILE_PATH, path);
        intent.putExtra(CLIP_WIDTH, width);
        intent.putExtra(CLIP_HEIGHT, height);
        return intent;
    }

    public static int[] getScreenDispaly(Context context) {
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();// 手机屏幕的宽度
        int height = windowManager.getDefaultDisplay().getHeight();// 手机屏幕的高度
        int result[] = {width, height};
        return result;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.ac_image_clip;
    }

    @Override
    protected void afterCreate(Bundle bundle) {
        if (InchingDataSingleCase.INSTANCE.getAppControl() != null) {
            imgNodeSizeMultiple = InchingDataSingleCase.INSTANCE.getAppControl().getImgNodeSizeMultiple();
        }
        filePath = getIntent().getStringExtra(FILE_PATH);
        if (!TextUtils.isEmpty(filePath) && (new File(filePath).exists())) {
            Glide.with(ImageClipActivity.this).asBitmap().load(filePath).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    if (resource == null) {
                        Toast.makeText(ImageClipActivity.this, "图片加载失败", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    cropLayout.setImage(resource);

                }
            });
            width = getIntent().getIntExtra(CLIP_WIDTH, 200);
            height = getIntent().getIntExtra(CLIP_HEIGHT, 200);
            Log.e("width-height", width + "-" + height);
            int screenWidth = getScreenDispaly(ImageClipActivity.this)[0];
            int screenHeight = getScreenDispaly(ImageClipActivity.this)[1];
            //宽高适应
            if (width >= screenWidth) {
                int cropHeight = (int) ((float) screenWidth / (float) width * (float) height);
                defineCropParams(screenWidth, cropHeight);
            } else if (height >= screenHeight) {
                int cropWidth = (int) ((float) height / (float) screenHeight * (float) width);
                defineCropParams(cropWidth, screenHeight);
            } else {
                defineCropParams(screenWidth, (int) ((float) screenWidth / (float) width * (float) height));
            }


        } else {
            Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
        }


    }

    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {

    }

    @OnClick({R.id.btn_cancel, R.id.btn_choose})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.btn_choose:
                showProgressDialogWithText("请稍等");
                saveClipBitMap();
                break;
        }
    }

    private void saveClipBitMap() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String name = AliRequestUtils.getInstance().createFileName("image", App.getLoginBean().getUserInfo().getUserId() + "") + ".png";
                AliRequestUtils.getInstance().setName(name);
                String url = "http://itbour-user.oss-cn-hangzhou.aliyuncs.com/";

                Bitmap lastBitmap;
                String lastPath;
                //裁剪图片，注意这里得到的图片并未进行任何压缩，是裁剪出来的原图大小
                Bitmap bitmap = cropLayout.crop(Float.parseFloat(width * imgNodeSizeMultiple + ""), Float.parseFloat(height * imgNodeSizeMultiple + ""));
                if (bitmap == null) {
                    handler.sendEmptyMessage(2);
                    return;
                }
                //保存图片
                lastBitmap = bitmap;
                //图片是否带透明通道 压缩输出方式不同
                String paths = AppCache.getInstance().mPicturesDir + File.separator + "/" + System.currentTimeMillis() + (bitmap.hasAlpha() ? ".png" : ".jpg");
                BitmapUtils.saveBitmaps(ImageClipActivity.this, bitmap, new File(paths));
                lastPath = paths;
                //保存的图片超过服务器最大规格图片大小 进行缩放
                if (bitmap.getWidth() > width * imgNodeSizeMultiple || bitmap.getHeight() > height * imgNodeSizeMultiple) {
                    boolean hasAlpha = bitmap.hasAlpha();
                    bitmap.recycle();
                    bitmap = null;
                    Bitmap resizeBitmap = BitmapUtils.resizeBitmap(paths, (int) (width * imgNodeSizeMultiple), (int) (height * imgNodeSizeMultiple));
                    lastBitmap = resizeBitmap;
                    String resizePath = AppCache.getInstance().mPicturesDir + File.separator + "/" + System.currentTimeMillis() + (hasAlpha ? ".png" : ".jpg");
                    BitmapUtils.saveBitmaps(ImageClipActivity.this, resizeBitmap, new File(resizePath));
                    lastPath = resizePath;
                    File file = new File(paths);
                    if (file.exists()) {
                        file.delete();
                    }
                }

                Long fileSizes = GetPath.getFileSizes(new File(lastPath));
                if (fileSizes != null) {
                    int defaultMaxSize = 5000000;
                    if (fileSizes > ((InchingDataSingleCase.INSTANCE != null && InchingDataSingleCase.INSTANCE.getAppControl() != null) ? InchingDataSingleCase.INSTANCE.getAppControl().getImgMaxSize() : defaultMaxSize)) {
                        handler.sendEmptyMessage(1);
                        return;
                    }
                }

                int bitH = 0;
                int bitW = 0;
                if (lastBitmap != null && lastBitmap.getHeight() != 0) {
                    bitH = lastBitmap.getHeight();
                }
                if (lastBitmap != null && lastBitmap.getWidth() != 0) {
                    bitW = lastBitmap.getWidth();
                }
                Intent intent = new Intent();
                try {
                    App.ossClient.putObject(AliRequestUtils.getInstance().putObjectRequest(lastPath));

                    intent.putExtra(AppConst.LOCAL_PHOTO_PATH, lastPath);
                    String pathName = url + name;
                    intent.putExtra(AppConst.LOCAL_PHOTO_PATH_NAME, pathName);
                    intent.putExtra(AppConst.PHOTO_BITMAP_W, bitW);
                    intent.putExtra(AppConst.PHOTO_BITMAP_H, bitH);
                    setResult(RESULT_OK, intent);

                } catch (ClientException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ImageClipActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (ServiceException e) {
                    e.printStackTrace();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ImageClipActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                if (!isFinishing()) {
                    dismissProgressDialog();
                    finish();
                }
            }
        }).start();
    }

    private void defineCropParams(int width, int height) {
        //设置裁剪集成视图，这里通过一定的方式集成了遮罩层与预览框
        BaseLayerView layerView = new ClipPathLayerView(this);
        layerView.setMask(ColorMask.getTranslucentMask()); //设置遮罩层,这里使用半透明的遮罩层
        layerView.setShape(new ClipPathRectangle(width, height)); //设置预览框形状
        cropLayout.setLayerView(layerView); //设置裁剪集成视图
        cropLayout.setRestrict(true, width, height); //设置边界限制，如果设置了该参数，预览框则不会超出图片
    }

    private void showImageTooBigDialog() {
        new OneToucDialog.Builder(ImageClipActivity.this)
                .content("图片文件过大，建议选择不超过" + (int) (InchingDataSingleCase.INSTANCE.getAppControl().getImgMaxSize() / 1000 / 1000) + "M的图片")
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false)
                .show();
    }

    private void showImageShouldCropDialog() {
        new OneToucDialog.Builder(ImageClipActivity.this)
                .content(DataCreater.imageMaxSize)
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false)
                .show();
    }
}
